package com.mindata.blockchain.core.sqlparser;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.mindata.blockchain.block.Operation;
import com.mindata.blockchain.common.CommonUtil;
import com.mindata.blockchain.core.model.GwUser;
import com.mindata.blockchain.core.model.MessageEntity;
import com.mindata.blockchain.core.repository.UserRepository;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 解析语句入库的具体实现，Message表的
 * @author wuweifeng wrote on 2018/3/21.
 */
@Service
public class UserSqlParser extends AbstractSqlParser<GwUser> {

    @Resource
    private UserRepository userRepository;

    @Override
    public void parse(byte operation, String uid, GwUser entity, String blockHash) {
         if (Operation.ADD == operation) {
        	 entity.setCreateTime(CommonUtil.getNow());
        	 entity.setCBlockHash(blockHash);
             userRepository.save(entity);
         } else if (Operation.DELETE == operation) {
             userRepository.deleteByUid(uid);
         } else if (Operation.UPDATE == operation) {
             GwUser userEntity = userRepository.findByUid(uid);
             BeanUtil.copyProperties(entity, userEntity, CopyOptions.create().setIgnoreNullValue(true).setIgnoreProperties("id", "createTime"));
             //修改密码记录区块HASH
             String oldPwd = userEntity.getUPassword();
             String newPwd = entity.getUPassword();
             if(StringUtil.isNotBlank(newPwd) && !newPwd.equals(oldPwd)){
                 entity.setUBlockHash(blockHash);
             }
             userRepository.save(userEntity);
         }
    }

    @Override
    public Class getEntityClass() {
        return GwUser.class;
    }

}
